<?php

namespace app\user\controller\user;

use app\admin\controller\Exception;
use app\common\controller\Userend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 题目分类
 *
 * @icon fa fa-circle-o
 */
class Questioncategory extends Userend
{

    /**
     * Questioncategory模型对象
     * @var \app\admin\model\Questioncategory
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Questioncategory;
    }


    /**
     * 查看
     */
    public function search()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $course_id = $this->request->param('course_id', 0);
            $extendWhere = [];
            if ($course_id) {
                $extendWhere['course_id'] = $course_id;
            }
            $list = $this->model
                ->where($where)
                ->where($extendWhere)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 查看列表
     */
    public function index()
    {
        // 请求参数
        $course_id = $this->request->param('ids', 0);

        // 检查参数
        if (!$course_id) {
            $this->error('非法请求');
        }

        // 生成树形数据

        $tree = Tree::instance();
        $tree->init($this->model->getListByCourseId($course_id), 'pid');
        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $searchValue = $this->request->request("searchValue");
            $search = $this->request->request("search");

            //构造父类select列表选项数据
            if ($search || $searchValue) {

                foreach ($list as $k => &$v) {

                    if ($search && stripos($v['name'], $search) !== false) {
                        $list[] = $v;
                    }
                    if ($searchValue && in_array($v['id'], explode(',', $searchValue)) !== false) {
                        $v['name'] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($v['name'])); //过滤空格
                        $list[] = $v;
                    }
                }
            }

            $list = array_values($list);
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);

        }

        $this->assign('course_id', $course_id);
        return $this->view->fetch();
    }

    public function select(){
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }


    /**
     * 添加
     */
    public function add()
    {
        // 上级编号
        $pid = $this->request->param('pid', 0);

        // 课程编号
        $parent_row = [];
        if ($pid > 0) {
            $parent_row = $this->model->find($pid);
            if (!$parent_row) {
                $this->error('上级信息不存在');
            }
            if ($parent_row['level'] + 1 > 3) {
                $this->error('不支持超过3级分类');
            }
            $course_id = $parent_row['course_id'];
        } else {
            $course_id = $this->request->param('ids', 0);
        }

        // 检查数据
        if (!$course_id) {
            $this->error('未获取到关联课程');
        }

        // 生成上级动态下拉参数
        $pid_data_params = 'data-params={"custom[course_id]":["eq","' . $course_id . '"]}';
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    //存在上级
                    $params['level'] = $parent_row ? $parent_row['level'] + 1 : 1;
                    $params['create_uid'] = getUserId();
                    $params['create_time'] = time();
                    $params['update_time'] = time();
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('pid', $pid);
        $this->view->assign('course_id', $course_id);
        $this->view->assign("pid_data_params", $pid_data_params);
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $uid = getUserId();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    // 检查数据归属
                    if ($row['create_uid'] != $uid) {
                        $this->error(__('您无权限修改本条数据'));
                    }

                    //如果上级变动
                    if (!empty($params['pid']) && $params['pid'] != $row['pid']) {
                        $parent_row = $this->model->find($params['pid']);
                        if (!$parent_row) {
                            $this->error('上级信息不存在');
                        }
                        $next_level = $parent_row['level'] + 1;
                        if ($next_level > 3) {
                            $this->error('不支持超过3级分类');
                        }
                        $params['level'] = $next_level;
                    }
                    $params['create_uid'] = $uid;
                    $params['update_time'] = time();

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 生成上级动态下拉参数
        $pid_data_params = 'data-params={"custom[course_id]":["eq","' . $row['course_id'] . '"]}';
        $this->view->assign("pid_data_params", $pid_data_params);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
